/**
 * Copyright (C) 2007 The AsyncMail Group <asyncmail@googlegroups.com>
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *         http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.googlecode.asyncmail.smtpserver.mina.filter;

import java.util.Timer;

import org.apache.mina.common.IoFilterAdapter;
import org.apache.mina.common.IoSession;
import org.springframework.beans.factory.annotation.Required;


public class TarpitFilter extends IoFilterAdapter {

    public final static String TARPIT_FILTER = "tarpitFilter";

    private long tarpitTime;

    private boolean removeFilter;

    public TarpitFilter() {
        this(false);
    }

    /**
     * Remove the filter after the write was tarpited if true was given as
     * constractor argument. Default is false
     * 
     * @param removeFilter
     */
    public TarpitFilter(boolean removeFilter) {
        this.removeFilter = removeFilter;
    }

    @Required
    public void setTarpitTime(long tarpitTime) {
        this.tarpitTime = tarpitTime;
    }

    @Override
    public void filterWrite(NextFilter arg0, IoSession arg1, WriteRequest arg2)
            throws Exception {
        Timer timer = new Timer();

        // Schedule the write
        timer.schedule(new FilterTarpitTimerTask(arg0, arg1, arg2), tarpitTime);
    }

    private class FilterTarpitTimerTask extends ThrottlingWriteTimerTask {

        public FilterTarpitTimerTask(NextFilter filter, IoSession session,
                WriteRequest request) {
            super(filter, session, request);
        }

        public void run() {
            super.run();

            // Remove filter if this is neccassary
            if (removeFilter) {
                session.getFilterChain().remove(TARPIT_FILTER);
            }

        }
    }
}
